package org.example.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.entity.PayPlan;
import org.example.entity.SysCoupon;
import org.example.entity.SysGoods;
import org.example.entity.TbCart;
import org.example.service.IPayPlanService;
import org.example.service.ISysCouponService;
import org.example.service.ISysGoodsService;
import org.example.service.ITbCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhaowenting
 * @since 2024-04-06
 */
@RestController
@RequestMapping("/tb-cart")
public class TbCartController {
    @Autowired
    ISysCouponService iSysCouponService;
    @Autowired
    IPayPlanService iPayPlanService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ISysGoodsService iSysGoodsService;
    @Autowired
    ITbCartService iTbCartService;
    //添加购物车
    @RequestMapping("toAddCart")
    public String toAddCart(Integer id,Integer userId){
        System.out.println("前端传过来的商品id=="+id);
        //根据ID去查询商品
        SysGoods sysGoods = iSysGoodsService.getById(id);
        //判断购物车是否有该商品
        final LambdaQueryWrapper<TbCart> tbCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tbCartLambdaQueryWrapper.eq(TbCart::getOrderNumber,sysGoods.getCropNumbering());
        tbCartLambdaQueryWrapper.eq(TbCart::getUserId,userId);
        TbCart tbCart = iTbCartService.getOne(tbCartLambdaQueryWrapper);
        //如果存在就修改数量
        if(tbCart!=null){
            //如果商品表的库存小于1就返回的话返回error不再往下执行
            if(sysGoods.getNum()<1){
                return "error";
            }
            //如果库存大于1 购物车的数量就加1
            tbCart.setBuyNum(tbCart.getBuyNum()+1);
            tbCart.setPrice(sysGoods.getPrice().multiply(new BigDecimal(tbCart.getBuyNum())));
            iTbCartService.updateById(tbCart);
            //商品表的库存减1
            sysGoods.setNum(sysGoods.getNum()-1);
            iSysGoodsService.updateById(sysGoods);
            return "success";
        }
        //在商品表里的库存大于1的时候
        if(sysGoods.getNum()<1){
            return "error";
        }
        //如果不存在就添加
        tbCart=new TbCart();
        tbCart.setBuyNum(1);
        tbCart.setUserId(userId);
        tbCart.setGoodsId(sysGoods.getId());
        tbCart.setOrderNumber(sysGoods.getCropNumbering());
        tbCart.setPrice(sysGoods.getPrice());
        iTbCartService.save(tbCart);

        sysGoods.setNum(sysGoods.getNum()-1);
        iSysGoodsService.updateById(sysGoods);
        return "success";
    }
    /*@RequestMapping("toAddCart")
    public String toAddCart(Integer id,Integer userId){
        System.out.println("前端传过来的商品id=="+id);
        //根据ID去查询商品
        SysGoods sysGoods = iSysGoodsService.getById(id);
        //判断优惠券表
        final LambdaQueryWrapper<SysCoupon> sysCouponLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysCouponLambdaQueryWrapper.le(SysCoupon::getEndTime,new Date());
        final SysCoupon sysCoupon = iSysCouponService.getOne(sysCouponLambdaQueryWrapper);
        //判断购物车是否有该商品
        final LambdaQueryWrapper<TbCart> tbCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tbCartLambdaQueryWrapper.eq(TbCart::getOrderNumber,sysGoods.getCropNumbering());
        tbCartLambdaQueryWrapper.eq(TbCart::getUserId,userId);
        TbCart tbCart = iTbCartService.getOne(tbCartLambdaQueryWrapper);
        //如果存在就修改数量
        if(tbCart!=null){
            //如果商品表的库存小于1就返回的话返回error不再往下执行
            if(sysGoods.getNum()<1){
                return "error";
            }
            //如果库存大于1 购物车的数量就加1
            tbCart.setBuyNum(tbCart.getBuyNum()+1);
            tbCart.setPrice(sysGoods.getPrice().multiply(new BigDecimal(tbCart.getBuyNum())));
            iTbCartService.updateById(tbCart);
            //商品表的库存减1
            sysGoods.setNum(sysGoods.getNum()-1);
            iSysGoodsService.updateById(sysGoods);
            return "success";
        }
        //在商品表里的库存大于1的时候
        if(sysGoods.getNum()<1){
            return "error";
        }
        //如果不存在就添加
        tbCart=new TbCart();
        tbCart.setBuyNum(1);
        tbCart.setUserId(userId);
        tbCart.setGoodsId(sysGoods.getId());
        tbCart.setOrderNumber(sysGoods.getCropNumbering());
        tbCart.setPrice(sysGoods.getPrice());
        iTbCartService.save(tbCart);

        sysGoods.setNum(sysGoods.getNum()-1);
        iSysGoodsService.updateById(sysGoods);
        return "success";
    }*/
//购物车列表
    @RequestMapping("cartList")
    public List<TbCart> cartList(){
        final List<TbCart> list = iTbCartService.cartList();
        return list;
    }
    //根据id删除购物车里的数据
    //购买数量为0时
    @RequestMapping("getByBuyNumDelCart")
    public String getByBuyNumDelCart(Integer id){
        iTbCartService.removeById(id);
        return "success";
    }

    /**
     * 修改购物车价格
     * @param buyNum
     * @param id
     * @return
     */
    @RequestMapping("changeBuyNum")
    public String changeBuyNum(Integer buyNum,Integer id){
        TbCart tbCart = iTbCartService.getById(id);
        //根据商品编号去查询对应的商品
        LambdaQueryWrapper<SysGoods> sysGoodsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sysGoodsLambdaQueryWrapper.eq(SysGoods::getCropNumbering,tbCart.getOrderNumber());
        SysGoods sysGoods = iSysGoodsService.getOne(sysGoodsLambdaQueryWrapper);

        if(buyNum>tbCart.getBuyNum()){
            if(sysGoods.getNum()<1){
                return "error";
            }
            sysGoods.setNum(sysGoods.getNum()-1);
            iSysGoodsService.updateById(sysGoods);
        }
        else{
            sysGoods.setNum(sysGoods.getNum()+1);
            iSysGoodsService.updateById(sysGoods);
        }

        tbCart.setBuyNum(buyNum);
        tbCart.setPrice(sysGoods.getPrice().multiply(new BigDecimal(tbCart.getBuyNum())));
        iTbCartService.updateById(tbCart);
        return "success";
    }
    //立即购买
    @RequestMapping("buyGoods")
    public Map buyGoods(){
        HashMap<String, Object> map = new HashMap<>();
        Integer userId = (Integer) redisTemplate.opsForValue().get("userId");
        System.out.println("用户id=="+userId);
        LambdaQueryWrapper<TbCart> tbCartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tbCartLambdaQueryWrapper.eq(TbCart::getUserId,userId);
        List<TbCart> list = iTbCartService.list(tbCartLambdaQueryWrapper);
        BigDecimal price = new BigDecimal("0");
        StringBuilder name = new StringBuilder();
        if(CollectionUtil.isNotEmpty(list)){
            for (TbCart tbCart : list) {
                SysGoods sysGoods = iSysGoodsService.getById(tbCart.getGoodsId());
                name.append(sysGoods.getCropName()+",");
                price=price.add(tbCart.getPrice());
            }
        }
        System.out.println("商品名称：==="+name);
        System.out.println("总金额为========"+price);
        PayPlan payPlan = new PayPlan();
        payPlan.setState(1);
        payPlan.setPrice(price);
        String cropName = name.substring(0, name.lastIndexOf(","));
        payPlan.setName(cropName);
        payPlan.setUserId(userId);
        payPlan.setCreateTime(new Date());
        payPlan.setOutTradeNo(IdUtil.getSnowflake().nextIdStr());
        iPayPlanService.save(payPlan);
        map.put("outTradeNo",payPlan.getOutTradeNo());
        map.put("msg","success");
        return map;
    }
}
